*-------------------------------------------------------------------------------
* TITLE: 2.tables.do
* DESCRIPTION: Code to create tables for main paper
* VERSION: MP17.0
* DATE: 08/26/21 
*-------------------------------------------------------------------------------



**------------------------------------------------------------------------------
** SETTINGS
**------------------------------------------------------------------------------
global Out "${Output}/tables"


**------------------------------------------------------------------------------
** TABLE 1: The Economic Lives of Women in Bangladeshi Villages at Baseline
**------------------------------------------------------------------------------

use "$Data/PovertyTraps_analysis.dta", clear

keep if survey_wave==1

	* prepare and label variables
gen inc_per_hour = total_income_resp / total_hours_work
gen inLabForce = total_hours_work>0
replace bmi=. if bmi>50									// exclude extreme outliers
replace pAssets = pAssets - (Pcows_no/1000) if stup==1 & treat==1 & survey==1
replace savings = savings/1000
gen loan_plus_pAssets = (loan_total_value/1000) + pAssets

label var inLabForce "In labour force"
label var total_hours_work "Total hours worked per year"
label var totalDays "Total days worked per year"
label var inc_per_hour "Hourly income (BDT)"
label var resp_educ_years "Years of formal education"
label var resp_literate "Literate"
label var bmi "Body mass index (BMI)"
label var pAssets "Productive assets (1000 BDT)"
label var savings "Household Savings (1000 BDT)"
label var loan_plus_pAssets "Productive assets + Loans (1000 BDT)"


	* create table
global labour inLabForce total_hours_work totalDays inc_per_hour
global capital	resp_educ_years resp_literate bmi savings pAssets loan_plus_pAssets

estimates clear
bysort sclass: eststo: estpost summarize $labour $capital

esttab using "${Out}/Labour_and_Capital_by_sclass.tex" ///
		, cells("mean(fmt(%12.2f))" "sd(par fmt(%12.2f))") ///
		label mlabels("ultra-poor" "near poor" "middle class" "upper-class") ///
		nonote  collabels( ,none) ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\linewidth}{l *4{>{\centering\arraybackslash}X}} \hline\hline")	///
	prefoot("\hline")  ///						
	postfoot("\hline\hline" "\end{tabularx} ") ///
	substitute(\_ _) fragment replace 


**------------------------------------------------------------------------------
** TABLE 2: Short-Term Responses to the Asset Transfer
**------------------------------------------------------------------------------

	* program to rename coefficients
cap prog drop rencoef
program rencoef, eclass
	syntax , coefnames(namelist)
	matrix b1 = e(b)
	matrix colnames b1 = `coefnames'
	matrix list b1
	ereturn repost b = b1, rename
end

	* define sample
use "${Data}/PovertyTraps_analysis.dta", clear
keep if stup==1 & survey==1

	* generate above Threshold 'placebo' for control
gen hh=ln(k0+(Pcows_no/1000)+1)
keep if hh<=3
gen aboveT=Lk1>=2.333 if Lk1!=.
replace aboveT= hh>2.333 if treat==0 & hh!=.

	* regressions columns 1, 3 and 
estimates clear
		
reg deltaLk3 aboveT if treat==1
estimates store est1_t

reg deltaLk3 aboveT if treat==0
estimates store est1_c

reg deltaLk3 i.treat##i.aboveT 
rencoef , coefnames("treat0" "treat" "aboveT0" "aboveT" "treat0XaboveT0" "treat0XaboveT" "treatXaboveT0" "treatXaboveT" "_cons") 
estimates store est1_b


	* regressions controlling for baseline assets (columns 2 & 4)
replace Lk1=Lk1-2.333

reg deltaLk3 i.aboveT##c.Lk1 if treat==1
rencoef , coefnames("aboveT0" "aboveT" "Lk1" "aboveT0XLk1" "aboveTXLk1" "_cons") 
estimates store est2_t
	
reg deltaLk3 i.aboveT##c.Lk1 if treat==0
rencoef , coefnames("aboveT0" "aboveT" "Lk1" "aboveT0XLk1" "aboveTXLk1" "_cons") 
estimates store est2_c


	* create table 
esttab est1_t est2_t est1_c  est2_c  est1_b ///
	using "${Out}\shorttermresponse_2Panel.tex" ///
	, cells(" b(star fmt(%12.3fc))"  	///
			" se(par fmt(%12.3fc))" ) 	///
	nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
	keep(aboveT treat treatXaboveT Lk1 aboveTXLk1  _cons) ///
	varlabels(aboveT "above \$ \hat{k}\$" treat "Treatment" treatXaboveT "Above \$ \hat{k}\$ \$\times\$ Treatment" Lk1 "Baseline assets" aboveTXLk1 "Above \$ \hat{k}\$ \$\times\$ Baseline assets" _cons "constant") ///
	mlabels("Treatment" "Treatment" "Control"  "Control"  "Both") ///
	prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\linewidth}{l *2{>{\centering\arraybackslash}X} @{\hskip 0.5cm} *3{>{\centering\arraybackslash}X} } \hline\hline" " & \multicolumn{5}{c}{\textit{Dependent variable: log change of productive assets 2007-2011}}  \\[1.5ex] \cline{2-6} \\[-1.5ex] & \multicolumn{2}{c}{\textbf{Panel A}} & \multicolumn{3}{c}{\textbf{Panel B}} \\ \cmidrule(r{10pt}){2-3} \cmidrule(l){4-6}")	///
	prefoot("\hline")  ///						
	postfoot("\hline\hline" "\end{tabularx} ") ///
	substitute(\_ _) fragment replace 



**------------------------------------------------------------------------------
** TABLE 3: Exploiting Individual Thresholds in Estimating Short-Term Responses 
** to the Asset Transfer
**------------------------------------------------------------------------------
	
* define programs to find thresholds -------------------------------------------
cap program drop findthrpoly_het
program define findthrpoly_het, rclass
	syntax varlist [if] [in], by(varname)
	
	local k2: word 1 of `varlist'
	local k1: word 2 of `varlist'
	
	tempvar k1_2 k1_3
	
	gen `k1_2' = `k1'^2
	gen `k1_3' = `k1'^3
	
	reg `k2' `k1' `k1_2' `k1_3' `by' `if' `in'
	
	local a1 = _b[_cons]
	local a2 = _b[_cons] + _b[`by']
	local b = _b[`k1'] - 1
	local c = _b[`k1_2']
	local d = _b[`k1_3']
	
	mata thrpoly(`a1', `b', `c', `d')
	return scalar thr_below = r(thr)
	
	mata thrpoly(`a2', `b', `c', `d')
	return scalar thr_above = r(thr)
end

cap mata mata drop thrpoly()
mata
	void thrpoly(real scalar a, real scalar b, real scalar c, real scalar d)
	{
		ss = polyroots((a, b, c, d))
		thr = Re(ss[2])
		st_numscalar("r(thr)", thr)
	}
end


* prepare dataset -------------------------------------------------------------

	* Define earnings potential as average cow returns at village level
tempfile cowR

use "$Data/PovertyTraps_analysis.dta", clear
keep if survey==1 & cows_no>0
gen cows_no2=cows_no^2
reg livestock_inc_tot cows_no cows_no2
predict cowMReturn, res
collapse (mean) cowMReturn, by(branchid spotno)
su cowMReturn,d
gen med_cowP=r(p50)
gen aboveM_cReturn=cowMReturn>med_cowP
save `cowR', replace


	* define sample 
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* merge earnings potential
merge m:1 branchid spotno using `cowR'
drop if _merge==2
drop _merge


	* prepare variables
		*  savings rate in yr 2 (2009)
gen savRate=savings/(savings+(pce_total*hhsize_adult_eq))
su savRate if survey==2 & treat & stup, d
gen aboveyr2med = savRate>r(p50) if survey==2 & savRate!=.
bysort hhid5: egen aboveM_savRate2 = max(aboveyr2med)
gen savRate2_yr = savRate if survey==2
bysort hhid5: egen savRate2 = max(savRate2_yr)
drop aboveyr2med savRate2_yr

keep if survey==1

		* Anxiety
tab H_anxietyD, m
gen no_anxiety = 1-H_anxietyD

		* Any formal education
gen any_educ = resp_educ_years>0


* find heterogeneous thresholds ------------------------------------------------

global vars aboveM_cReturn aboveM_savRate2  no_anxiety any_educ 

	* regressions loop
foreach v of global vars {
	
	reg Lk3 c.Lk1##c.Lk1##c.Lk1  `v' 
	cap drop pred_`v'	
	predict pred_`v'

	findthrpoly_het Lk3 Lk1, by(`v')
	global khatLow_`v' = r(thr_above)
	global khatHigh_`v' = r(thr_below)

}

	* define individual thresholds 
foreach v of global vars {
	cap drop khatI_`v'
	cap drop abovekI_`v'
	cap drop abovekLow_`v'
	cap drop abovekHigh_`v'
	
	gen khatI_`v' = ${khatHigh_`v'} if `v'==0
	replace khatI_`v' = ${khatLow_`v'} if `v'==1
	gen abovekI_`v' = Lk1 > khatI_`v'
	
	gen abovekLow_`v' = Lk1>${khatLow_`v'}
	gen abovekHigh_`v' = Lk1>${khatHigh_`v'} 
}

	* define individual thresholds combined
cap drop Lk1_2
cap drop Lk1_3
gen Lk1_2 = Lk1^2
gen Lk1_3 = Lk1^3

reg Lk3 Lk1 Lk1_2 Lk1_3 ${vars} 
local a = _b[_cons]
local b = _b[Lk1]-1
local c = _b[Lk1_2]
local d = _b[Lk1_3]

tempvar intercept 
gen `intercept' = `a' if e(sample)
foreach v of global vars {
	local b_`v' = _b[`v']
	replace `intercept' = `intercept' + `b_`v'' if `v'==1	
}
levelsof `intercept', local(ints)
gen khatI_all =.
foreach i of local ints {
	mata thrpoly(`i', `b', `c', `d')
	replace khatI_all = r(thr) if `intercept'==`i'
}
gen abovekI_all = Lk1 > khatI_all 
		

* regressions ------------------------------------------------------------------
global regvars aboveM_cReturn aboveM_savRate2 no_anxiety any_educ all
local estlist
foreach v of global regvars {
    
	cap drop this_kI
	gen this_kI = abovekI_`v'
		
		* unconditional
	reg deltaLk3 this_kI if treat==1 & stup==1 & Lk1<3, robust
	eststo est_`v'
	
		* with baseline K FE
	areg deltaLk3 this_kI  if treat==1 & stup==1 & Lk1<=3, a(Lk0) robust
	eststo est_`v'_FE
	
	local estlist `estlist' est_`v' est_`v'_FE
}

	* create table
esttab 	`estlist' ///
	using "${Out}/heterogeneous_thresholds.tex", ///
	varlabels(this_kI "Above \$ \hat{k_{i}} \$" _cons "Constant")  ///
	prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\linewidth}{l *{10}{>{\centering\arraybackslash}X}  } \hline\hline")			/// 
	posthead("& \multicolumn{2}{c}{Earnings Potential} & \multicolumn{2}{c}{Savings Rate} & \multicolumn{2}{c}{No Anxiety} & \multicolumn{2}{c}{Any Education} & \multicolumn{2}{c}{Combined} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} \cmidrule(lr){8-9} \cmidrule(lr){10-11} \\") ///
	fragment nomtitles substitute(\_ _) ///
	prefoot("\hline Baseline \$ k \$ FE & NO & YES & NO & YES & NO & YES & NO & YES & NO & YES \\ ") ///
	postfoot("\hline\hline \end{tabularx} ") ///
	replace		

		
**------------------------------------------------------------------------------
** TABLE 4: Difference in Differences Estimates of Long-Run Dynamics
**------------------------------------------------------------------------------

	* define sample
use "$Data/PovertyTraps_analysis.dta", clear
keep if stup==1 & treat==1 & Lk1<=3

	* prepare variables
gen aboveT=Lk1>=2.333 if Lk1!=.
replace pAssets = pAssets * 1000
gen HHconsumption = pce_total * hhsize_adult_eq
gen HHfoodcons = pce_food * hhsize_adult_eq
gen sh=(livestock_hours_tot +hhlandcult_hours_tot)

	* regression loop
estimates clear	
local vars pAssets cows_value land_own_total_value HHconsumption income_resp_total selfemp_inc_tot total_hours_work sh
local regs
foreach v of local vars {
	
	areg `v' i.survey##i.aboveT , a(subdistrict) robust coeflegend
	est sto mod_`v'
	local regs `regs' mod_`v'
	
	* test dynamic differences
	test 2.survey_wave#1.aboveT = 3.survey_wave#1.aboveT
	local test3 = r(p)
	test 2.survey_wave#1.aboveT = 4.survey_wave#1.aboveT
	local test4 = r(p)
	test 2.survey_wave#1.aboveT = 5.survey_wave#1.aboveT
	local test5 = r(p)
	
	* relabel test results
	foreach t in 3 4 5 {
	    if `test`t''<0.01 {
		    local tout`t' = "\$ < 0.01 \$"
		}
		else {
		    local tout`t' = string(`test`t'', "%6.3f")
		}
			
		estadd local test`t' "`tout`t''"
	}
	
}
 
 	* create table
esttab `regs' using "${Out}/LongTerm_all.tex"	///
		, cells(" b(star fmt(%12.0fc))"  	///
				" se(par fmt(%12.0fc))" ) 	///
		keep(2.survey_wave#1.aboveT 3.survey_wave#1.aboveT 4.survey_wave#1.aboveT 5.survey_wave#1.aboveT) ///
		nonote  collabels( ,none) starlevels("*" 0.10 "**" 0.05 "***" 0.01) ///
		mlabels("Productive assets" "Cows" "Land" "Cons." "Net Earnings" "Net Earnings self-empl." "Total hours" "Hours self-empl." ) ///
		varlabels( 2.survey_wave#1.aboveT "Year 2 \$\times \$ above \$ \hat{k} \$" 3.survey_wave#1.aboveT "Year 4 \$\times \$ above \$ \hat{k} \$" 4.survey_wave#1.aboveT "Year 7 \$\times \$ above \$ \hat{k} \$" 5.survey_wave#1.aboveT "Year 11 \$\times \$ above \$ \hat{k} \$" ) ///
		scalars("test3 p-value year 2 vs. 4" "test4 p-value year 2 vs. 7" "test5 p-value year 2 vs. 11") ///
		prehead("\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" "\begin{tabularx}{\textwidth}{l *8{>{\centering\arraybackslash}X}  } \hline\hline")			/// 
		fragment ///
		prefoot("\hline") ///
		postfoot("\hline\hline \end{tabularx} ") ///
		replace		

